package com.parfinex.study.p2.mod201.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtils {

    //1.定义成员变量
    public static DataSource dataSource;
    //2.静态代码块
    static {

        try {
            //2.1创建属性集对象
            Properties properties = new Properties();
            //2.2加载配置文件 Druid连接池不能主动加载配置文件，需要指定文件
            InputStream inputStream = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
            //2.3使用properties对象的load方法，从字节流中读取文件
            properties.load(inputStream);
            //2.4.通过工厂方法获取连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //3.获取连接的方法
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    //4.获取Druid连接池对象的方法
    public static DataSource getDataSource() { return dataSource; }

    //5.释放资源
    public static void close(Connection con,Statement statement) {
        if (null != con && null !=statement){
            try {
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Connection con,Statement statement,ResultSet resultSet){
        if (null != con && null != statement && null != resultSet){
            try {
                resultSet.close();
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
